package C049;

/**
 * ClassName: C05
 * Package: C049
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/17 13:56
 * @Version 1.0
 * @Since 1.0
 */
public class C05 {
    public static void main(String[] args) {
        System.out.println(balancedString("QQWE"));
    }


    public static int balancedString(String s) {
        char[] charArray = s.toCharArray();
        int[] cnt = new int[4];
        int index ;
        for (int i = 0; i < charArray.length; i++) {
             index = getIndex(charArray[i]);
             cnt[index]++;
        }

        int req = charArray.length / 4, debt = 0;
        // 处理cnt
        for (int i = 0; i < cnt.length; i++) {
            if(cnt[i] < req) {
                cnt[i] = 0;
            } else {
                cnt[i] = req - cnt[i];
                debt += cnt[i];
            }
        }

        int len = Integer.MAX_VALUE, start = Integer.MAX_VALUE;
        for (int i = 0, l = 0; i < charArray.length; i++) {
            if(cnt[getIndex(charArray[i])]++ < 0) {
                debt ++;
            }
            if(debt == 0) {
                // 最小化数组
                // 字符串是否能够压缩
                while(l < charArray.length && cnt[getIndex(charArray[l])] > 0) {
                    cnt[getIndex(charArray[l++])] --;
                }
                if(i - l + 1 < len) {
                    len = i - l + 1;
                    start = l;
                }

            }
        }
        return len == Integer.MAX_VALUE ? 0 : len;
    }

    private static int getIndex(char c) {
        if(c == 'Q') {
            return 0;
        } else if(c == 'W') {
            return 1;
        } else if(c == 'E') {
            return 2;
        } else if(c == 'R') {
            return 3;
        }

        return -1;
    }
}
